package global

import (
	"bytes"
	"compress/flate"
	"compress/gzip"
	"gitee.com/swsk33/sclog"
	"github.com/andybalholm/brotli"
	"io"
	"net/http"
	"time"
)

// httpClient 全局HTTP客户端
var httpClient = &http.Client{
	Timeout: 20 * time.Minute,
	Transport: &http.Transport{
		Proxy: http.ProxyFromEnvironment,
	},
}

// 检测返回的请求体是否经过压缩，并返回解压的内容
// response 响应对象
func decodeCompressedBody(response *http.Response) io.Reader {
	encoding := response.Header.Get("Content-Encoding")
	body := response.Body
	var bodyReader io.Reader
	switch encoding {
	case "gzip":
		bodyReader, _ = gzip.NewReader(body)
	case "deflate":
		bodyReader = flate.NewReader(body)
	case "br":
		bodyReader = brotli.NewReader(body)
	default:
		bodyReader = response.Body
	}
	return bodyReader
}

// 全局请求前缀常量
const (
	// AuthEndpoint 登录认证端点
	AuthEndpoint = "https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token"
	// ProductQuery 产品查询端点
	ProductQuery = "https://catalogue.dataspace.copernicus.eu/odata/v1/Products"
)

// 请求体类型
const (
	JSON       = "application/json"
	UrlEncoded = "application/x-www-form-urlencoded"
)

// RefreshToken 刷新Token
var RefreshToken = ""

// SendRequest 发送HTTP请求
//
//   - url 请求地址
//   - method 请求类型，例如 http.MethodGet http.MethodPost 等
//   - contentType 请求体类型
//   - body 请求体，无请求体传入nil
func SendRequest(url, method, contentType string, body []byte) ([]byte, error) {
	// 准备请求
	var reader io.Reader
	if body != nil {
		reader = bytes.NewReader(body)
	}
	request, e := http.NewRequest(method, url, reader)
	if e != nil {
		sclog.ErrorLine("准备请求出错！")
		return nil, e
	}
	request.Header.Set("Content-Type", contentType)
	// 发请求
	response, e := httpClient.Do(request)
	if e != nil {
		sclog.ErrorLine("发送请求出错！")
		return nil, e
	}
	defer func() {
		_ = response.Body.Close()
	}()
	// 解析响应体
	bodyReader := decodeCompressedBody(response)
	result, e := io.ReadAll(bodyReader)
	if e != nil {
		sclog.ErrorLine("读取响应体出错！")
		return nil, e
	}
	return result, nil
}